import { Provide, Inject } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';

import { MallProductService } from '../../mall/service/product';
import { FavoritePageDto } from '../dto/favorite';
import { CustomerFavoriteEntity } from '../entity/favorite';

@Provide()
export class CustomerFavoriteService {
  @InjectEntityModel(CustomerFavoriteEntity)
  customerFavoriteRepository: Repository<CustomerFavoriteEntity>;

  @Inject()
  mallProductService: MallProductService;

  async info(id: number) {
    const favorite = await this.customerFavoriteRepository.findOne(id, {
      select: ['productId'],
    });
    return await this.mallProductService.info(favorite.productId);
  }

  async page(pageOp: FavoritePageDto) {
    const count = await this.customerFavoriteRepository.count({
      customerId: pageOp.customerId,
    });
    // 取得 productId[]
    const ids = (
      await this.customerFavoriteRepository.find({
        where: { customerId: pageOp.customerId },
        select: ['productId'],
        skip: pageOp.start,
        take: pageOp.limit,
        order: { createTime: 'DESC' },
      })
    ).map(v => v.productId);
    // 调用服务，获取每个 product 的信息
    const data = Promise.all(
      ids.map(async productId => {
        return await this.mallProductService.info(productId);
      })
    );
    return { count, data };
  }
}
